package com.ruoyi.system.service.impl.fxImpl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.fx.FxGoodclassify;
import com.ruoyi.system.mapper.fx.FxGoodclassifyMapper;
import com.ruoyi.system.service.fx.IFxGoodModelService;
import com.ruoyi.system.service.fx.IFxGoodclassifyService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 商品分类Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-23
 */
@Service
public class FxGoodclassifyServiceImpl implements IFxGoodclassifyService {
    @Autowired
    private FxGoodclassifyMapper fxGoodclassifyMapper;
    @Autowired
    private IFxGoodModelService fxGoodModelService;

    /**
     * 查询商品分类
     *
     * @param id 商品分类主键
     * @return 商品分类
     */
    @Override
    public FxGoodclassify selectFxGoodclassifyById(Long id) {
        return fxGoodclassifyMapper.selectFxGoodclassifyById(id);
    }

    /**
     * 查询商品分类列表
     *
     * @param fxGoodclassify 商品分类
     * @return 商品分类
     */
    @Override
    public List<FxGoodclassify> selectFxGoodclassifyList(FxGoodclassify fxGoodclassify) {
        return fxGoodclassifyMapper.selectFxGoodclassifyList(fxGoodclassify);
    }

    /**
     * 上传 excel
     *
     * @param file
     */
    @Override
    public void importData(MultipartFile file) {

        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new GlobalException("上传的文件为空");
        }
        try (InputStream inputStream = file.getInputStream()) {
            Workbook workbook = new XSSFWorkbook(inputStream); // 支持.xlsx格式的Excel文件

            // 遍历每个工作表
            for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
                Sheet sheet = workbook.getSheetAt(sheetIndex);

                String sheetName = sheet.getSheetName();
                System.out.println("工作页：---- " + sheet.getSheetName());

                // 读取数据行
                List<Map<String, Object>> dataList = new ArrayList<>();
                System.out.println("行数：------" + sheet.getLastRowNum());
                for (int i = 0; i <= sheet.getLastRowNum(); i++) {
                    Row dataRow = sheet.getRow(i);
                    if (dataRow == null) {
                        continue; // 跳过空行
                    }
                    Map<String, Object> rowData = new LinkedHashMap<>(); // 使用LinkedHashMap保持插入顺序

                    // 读取每一列的数据
                    for (int j = 0; j < dataRow.getLastCellNum(); j++) {
                        Cell cell = dataRow.getCell(j);

                        // 根据单元格类型处理数据
                        if (cell == null) {
//                            rowData.put("Column" + (j + 1), ""); // 如果单元格为空，可以设置一个默认值
                        } else {
                            switch (cell.getCellType()) {
                                case STRING:
                                    rowData.put("Column" + (j + 1), cell.getStringCellValue().trim());
                                    break;
                                case NUMERIC:
                                    rowData.put("Column" + (j + 1), cell.getNumericCellValue());
                                    break;
                                // 其他类型的单元格处理
                            }
                        }
                    }
                    // 不是空map 插入
                    if (StringUtils.isNotEmpty(rowData)) {
                        dataList.add(rowData); // 将一行数据添加到列表中
                    }
                }

                // 进行数据处理，这里可以根据业务需求将dataList存入数据库或者进行其他操作
                if (StringUtils.isNotEmpty(dataList)) {
                    System.out.println(dataList);
                    importFxGoodClassify(sheetIndex, sheetName, dataList); // 插入数据库
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new GlobalException("文件读取错误");
        }


    }

    /**
     * 导入数据
     *
     * @param sheetName 类名称
     * @param dataList  子类数据
     * @return
     */
    public int importFxGoodClassify(Integer sheetIndex, String sheetName, List<Map<String, Object>> dataList) {

        System.out.println("排序：===" + sheetIndex);
        System.out.println("一级名：====" + sheetName);
        String userName = SecurityUtils.getUsername();

        // 插入父分类
        FxGoodclassify fxGoodclassify = new FxGoodclassify();
        fxGoodclassify.setAncestors("0");
        fxGoodclassify.setTier(0);
        fxGoodclassify.setDeptName(sheetName);
        fxGoodclassify.setSort(Convert.toLong(sheetIndex));
        fxGoodclassify.setCreateBy(userName);
        fxGoodclassify.setCreateTime(DateUtils.getNowDate());
        fxGoodclassifyMapper.insertFxGoodclassify(fxGoodclassify);
        Long pId = fxGoodclassify.getId();
        Long twoId = null;
        Long twoSort = 0L;
        Long threeSort = 0L;
        for (Map<String, Object> objectMap : dataList) {
            List<String> idList = new ArrayList<>();
            idList.add("0");

            Object o2 = objectMap.get("Column2");
            Object o3 = objectMap.get("Column3");
            if (StringUtils.isNotNull(o2)) {
                System.out.println("二级： ========= " + o2);
                idList.add(pId.toString());
                twoSort++;
                threeSort = 0L;
                FxGoodclassify goodClassify = createGoodClassify(pId, idList, userName, o2.toString(), 1, twoSort);
                fxGoodclassifyMapper.insertFxGoodclassify(goodClassify);
                twoId = goodClassify.getId();
            }
            if (StringUtils.isNotNull(o3)) {
                idList.add(pId.toString());
                idList.add(twoId.toString());
                threeSort++;
                FxGoodclassify classify = createGoodClassify(twoId, idList, userName, o3.toString(), 2, threeSort);
                fxGoodclassifyMapper.insertFxGoodclassify(classify);
            }
        }
        return 0;
    }

    private FxGoodclassify createGoodClassify(Long parentId, List<String> idList, String userName, String deptName, int tier, Long sort) {
        String ancestors = String.join(",", idList);
        FxGoodclassify classify = new FxGoodclassify();
        classify.setParentId(parentId);
        classify.setAncestors(ancestors);
        classify.setTier(tier);
        classify.setDeptName(deptName);
        classify.setSort(sort);
        classify.setCreateBy(userName);
        classify.setCreateTime(DateUtils.getNowDate());
        return classify;
    }


    /**
     * 校验名称是否唯一
     *
     * @param fxGoodclassify 商品分类名称
     * @return
     */
    @Override
    public boolean checkNameUnique(FxGoodclassify fxGoodclassify) {
        Long classifyId = StringUtils.isNull(fxGoodclassify.getId()) ? -1L : fxGoodclassify.getId();
        FxGoodclassify info = fxGoodclassifyMapper.checkNameUnique(fxGoodclassify.getDeptName(), fxGoodclassify.getParentId());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != classifyId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 查询全部子节点状态
     *
     * @param id id
     * @return
     */
    @Override
    public int checkAllChildNodeStatusById(Long id) {
        return fxGoodclassifyMapper.checkAllChildNodeStatusById(id);
    }

    /**
     * 新增商品分类
     *
     * @param fxGoodclassify 商品分类
     * @return 结果
     */
    @Override
    public int insertFxGoodclassify(FxGoodclassify fxGoodclassify) {
        // 查询当前新增 父节点信息
        FxGoodclassify info = fxGoodclassifyMapper.selectFxGoodclassifyById(fxGoodclassify.getParentId());
        // 如果父节点为不正常状态，不允许新增子节点
        fxGoodclassify.setCreateTime(DateUtils.getNowDate());
        if (info != null) {
            if (!UserConstants.NORMAL.equals(info.getDelFlag())) {
                throw new ServiceException("分类停用，不允许新增");
            }
        } else {
            fxGoodclassify.setAncestors("0");
            fxGoodclassify.setTier(0);
            return fxGoodclassifyMapper.insertFxGoodclassify(fxGoodclassify);
        }
        String[] ancestors = info.getAncestors().split(",");
        fxGoodclassify.setAncestors(info.getAncestors() + "," + fxGoodclassify.getParentId());
        fxGoodclassify.setTier(ancestors.length);
        return fxGoodclassifyMapper.insertFxGoodclassify(fxGoodclassify);
    }

    /**
     * 修改商品分类
     *
     * @param fxGoodclassify 商品分类
     * @return 结果
     */
    @Override
    public int updateFxGoodclassify(FxGoodclassify fxGoodclassify) {
        // 获取 oldData
        FxGoodclassify oldData = fxGoodclassifyMapper.selectFxGoodclassifyById(fxGoodclassify.getId());
        if (!Objects.equals(oldData.getParentId(), fxGoodclassify.getParentId())) { // 判断修改 父id 是否改变
            // 改变 查询父数据
            FxGoodclassify info = fxGoodclassifyMapper.selectFxGoodclassifyById(fxGoodclassify.getParentId());
            // 拿到 旧祖级列表
            String oldAncestors = oldData.getAncestors();
            // 计算新 祖级列表
            String newAncestors = info.getAncestors() + "," + fxGoodclassify.getParentId();
            // 调用方法 修改全部子级数据
            updateChildren(oldData.getId(), newAncestors, oldAncestors);
            fxGoodclassify.setAncestors(newAncestors);
        }
        if (1 != fxGoodclassify.getStatus() && StringUtils.isNotEmpty(fxGoodclassify.getAncestors())
                && !StringUtils.equals("0", fxGoodclassify.getAncestors())) {
            // 如果该分类是启用状态，则启用该分类的所有上级分类
            updateParentStatusNormal(fxGoodclassify);
        }
        fxGoodclassify.setUpdateTime(DateUtils.getNowDate());
        return fxGoodclassifyMapper.updateFxGoodclassify(fxGoodclassify);
    }

    /**
     * 修改子元素关系
     *
     * @param id           被修改的分类ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateChildren(Long id, String newAncestors, String oldAncestors) {
        List<FxGoodclassify> children = fxGoodclassifyMapper.selectChildrenById(id);
        for (FxGoodclassify classify : children) {
            classify.setAncestors(classify.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            fxGoodclassifyMapper.updateChildrenList(children);
        }
    }

    /**
     * 修改该分类的父级分类状态
     *
     * @param fxGoodclassify 当前商品分类
     */
    private void updateParentStatusNormal(FxGoodclassify fxGoodclassify) {
        String ancestors = fxGoodclassify.getAncestors();
        Long[] ids = Convert.toLongArray(ancestors);
        fxGoodclassifyMapper.updateStatusByIds(ids, 0, 0);
    }

    /**
     * 批量删除商品分类
     *
     * @param ids 需要删除的商品分类主键
     * @return 结果
     */
    @Override
    public int deleteFxGoodclassifyByIds(Long[] ids) {
        List<Long> classifyIds = new ArrayList<>();
        for (Long id : ids) {
            List<FxGoodclassify> classify = fxGoodclassifyMapper.selectClassify(id);
            classifyIds.addAll(classify.stream().map(FxGoodclassify::getId).collect(Collectors.toList()));
        }
        ids = classifyIds.stream().distinct().toArray(Long[]::new);
        // 删除同时删除掉模板库数据
        fxGoodModelService.deleteFxGoodModelByClassifyIds(ids);
        return fxGoodclassifyMapper.updateStatusByIds(ids, 1, 1);
//        return fxGoodclassifyMapper.deleteFxGoodclassifyByIds(ids);
    }

    /**
     * 删除商品分类信息
     *
     * @param id 商品分类主键
     * @return 结果
     */
    @Override
    public int deleteFxGoodclassifyById(Long id) {
        return fxGoodclassifyMapper.deleteFxGoodclassifyById(id);
    }

    @Override
    public List<FxGoodclassify> selectGoodClassTree(FxGoodclassify fxGoodclassify, List<FxGoodclassify> goodList) {
        fxGoodclassify.setParentId(0L);
        // 查询所有节点
        List<FxGoodclassify> allNodes = fxGoodclassifyMapper.selectFxGoodclassifyList(fxGoodclassify);

        // 创建一个map，将所有节点按父节点分组
        Map<Long, List<FxGoodclassify>> groupedByParentId = goodList.stream()
                .collect(Collectors.groupingBy(FxGoodclassify::getParentId));

        for (FxGoodclassify topNode : allNodes) {
            List<FxGoodclassify> childList = buildTree(topNode.getId(), groupedByParentId);
            topNode.setChildList(childList);
        }
        Long parentId = fxGoodclassify.getId() != null ? fxGoodclassify.getId() : 0L;

        // 从根节点开始构建树
        return buildTree(parentId, groupedByParentId);
    }

    private List<FxGoodclassify> buildTree(Long parentId, Map<Long, List<FxGoodclassify>> groupedByParentId) {
        List<FxGoodclassify> children = groupedByParentId.get(parentId);
        if (CollectionUtils.isEmpty(children)) {
            return Collections.emptyList();
        }
        for (FxGoodclassify child : children) {
            // 递归构建子节点
            List<FxGoodclassify> childList = buildTree(child.getId(), groupedByParentId);
            child.setChildList(childList);
        }
        return children;
    }


}
